package com.bitcointoolkit.web.controller;

import com.alibaba.fastjson.JSON;
import com.bitcointoolkit.common.cash.BechCashUtil;
import com.bitcointoolkit.web.service.AddrInfoService;
import com.bitcointoolkit.web.service.UtxoResult;
import com.bitcointoolkit.web.support.ErrorEnum;
import com.bitcointoolkit.web.support.ErrorResult;
import com.bitcointoolkit.web.support.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 */
@Controller
@RequestMapping("/wallet")
public class WalletInfoController extends BaseController {

    private final static BechCashUtil CASH = BechCashUtil.getInstance();

    @Autowired
    AddrInfoService addrInfoService;
    /**
     * @param model
     * @param address 仅支持legacy 格式
     * @return
     */
    @RequestMapping({"/listUtxo"})
    @ResponseBody
    public String listUtxo(Model model, @RequestParam(value = "address") String address,
                           @RequestParam(value = "page", required = false) Integer page,
                           @RequestParam(value = "pagesize",required = false) Integer pagesize) {
        try {
            CASH.checkLegacy(address);
        } catch (IllegalArgumentException e) {
            logger.warn("listUtxo 地址格式错误:"+address + " --- "+e.getMessage());
            return new ErrorResult(ErrorEnum.ADDRESS_INVALID).toString();
        }

        if (page == null || page <1) {
            page = 1;
        }
        if (pagesize == null || pagesize <1) {
            pagesize = 50;
        }
        Result<UtxoResult> result = addrInfoService.listUtxo(address, page, pagesize);
        if (result.isSuccess()) {
            return JSON.toJSONString(result.getData());
        } else {
            return new ErrorResult(ErrorEnum.QUERY_FAILED).toString();
        }
    }

    @RequestMapping({"/tolegacy"})
    @ResponseBody
    public String convertToLeagcy(Model model, @RequestParam(value = "address") String address) {
        if (address == null || address.length() < 40 || address.length() > 60) {// 没计算具体长度 大概估计一个范围
            return new ErrorResult(ErrorEnum.ADDRESS_INVALID).toString();
        }
        int idx = address.indexOf(':');
        String formatted = address;
        if (idx == -1) {
            formatted = "bitcoincash:" + address;
        } else {
            String prefix = address.substring(0, idx);
            if ( !"bitcoincash".equals(prefix) && !"bchtest".equals(prefix)) {
                return new ErrorResult(ErrorEnum.INVALID_PREFIX).toString();
            }
        }

        try {
            String legacy = CASH.transferCashAddrToLegacy(formatted);

            AddressInfo addressInfo = new AddressInfo();
            addressInfo.setCashaddr(formatted);
            addressInfo.setLegacy(legacy);

            return JSON.toJSONString(addressInfo);
        } catch (Exception e) {
            logger.error("tolegacy " + address,e);
            return new ErrorResult(ErrorEnum.CONVERT_ERROR).toString();
        }
    }


    @RequestMapping({"/tocashaddr"})
    @ResponseBody
    public String convertToCashaddr(Model model, @RequestParam(value = "address") String address) {
        if (address == null || address.length() < 33 || address.length() > 34) {
            return new ErrorResult(ErrorEnum.ADDRESS_INVALID).toString();
        }

        try {
            String cashAddr = CASH.transferLegacyToCashAddr(address);

            AddressInfo addressInfo = new AddressInfo();
            addressInfo.setCashaddr(cashAddr);
            addressInfo.setLegacy(address);

            return JSON.toJSONString(addressInfo);
        } catch (Exception e) {
            logger.error("tocashaddr " + address,e);
            return new ErrorResult(ErrorEnum.CONVERT_ERROR).toString();
        }
    }

}
